﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using He.Web.UI;
using He.Common;
using System.Web.Security;
using He.API.OAuth.QQHelper;

namespace He.Web.user.oauth.qq
{
    public partial class reg : System.Web.UI.Page
    {
        BLL.member mbll = new BLL.member();
        QQHelper Helper = new QQHelper();
        public string openid = "";
        public string access_token = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                GetReturn();
            }

            if (this.Session["access_token"] == null || this.Session["access_token"].ToString() == string.Empty || this.Session["openid"] == null || this.Session["openid"].ToString() == string.Empty)
            {
                Response.Write("<script>alert('信息超时，请重新发送请求')</script>");
                Response.End();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.access_token = this.Session["access_token"].ToString();
            this.openid = this.Session["openid"].ToString();

            Model.webset webset = new BLL.webset().GetWebset();

            Dictionary<string, object> dic = Helper.get_user_info(access_token, openid);

            if (dic != null)
            {
                string username = txtUsername.Text.Trim();
                Model.member member = new Model.member();

                if (mbll.Exists(username))
                {
                    lblMsg.Text = "用户名已经存在，请使用其他用户名！";
                    return;
                }
                if (mbll.ExistsEmail(txtEmail.Text.Trim()))
                {
                    lblMsg.Text = "该邮箱已被使用，请使用其他邮箱！";
                    return;
                }

                member.user_name = username;
                member.user_pwd = CryptoHelper.DESEncrypt(txtUserPwd.Text.Trim());
                member.email = txtEmail.Text.Trim();
                member.qq_openid = openid;
                member.figure_url = dic["figureurl_2"].ToString();
                member.nickname = dic["nickname"].ToString();
                member.sex = dic["gender"].ToString();
                member.status = webset.member_reg_status;
                member.reg_time = DateTime.Now.ToString();
                mbll.Add(member);

                if (member.status == (int)Enums.MemberStatus.Email验证)
                {
                    member.status = (int)Enums.MemberStatus.正常;
                }
                if (member.status == (int)Enums.MemberStatus.人工审核)
                {
                    Response.Redirect("/user/reg_check.aspx?status=" + Enums.MemberStatus.人工审核.ToString());
                }
                else if (member.status == (int)Enums.MemberStatus.冻结)
                {
                    Response.Redirect("/user/reg_check.aspx?status=" + Enums.MemberStatus.冻结.ToString());
                }
                else
                {
                    CookieHelper.Set("username", username);
                    //设置验证Cookie并跳转
                    FormsAuthentication.RedirectFromLoginPage(member.user_name, false);
                }
            }
            else
            {
                Response.Write("获取user_info失败！");
                Response.End();
            }
        }

        private void GetReturn()
        {
            //若access_token和appid已存在于Session中，直接读取，否则根据code获取
            string code = base.Request["code"];

            if (!string.IsNullOrEmpty(code))
            {
                if (base.Request["state"] == this.Session["state"].ToString())
                {
                    Dictionary<string, object> dic1 = Helper.get_access_token(code, "reg.aspx");
                    if (dic1 != null)
                    {
                        access_token = dic1["access_token"].ToString();
                        this.Session["access_token"] = access_token;
                    }
                    else
                    {
                        Response.Write("获取access token值失败！");
                        Response.End();
                    }
                    Dictionary<string, object> dic2 = Helper.get_open_id(access_token);
                    if (dic2 != null)
                    {
                        openid = dic2["openid"].ToString();
                        this.Session["openid"] = openid;
                        GetInfo(access_token, openid);
                    }
                    else
                    {
                        Response.Write("获取openid值失败！");
                        Response.End();
                    }
                }
                else
                {
                    Response.Write("status不匹配");
                    Response.End();
                }
            }

        }

        private void GetInfo(string _access_token, string _openid)
        {
            Dictionary<string, object> dic = Helper.get_user_info(_access_token, _openid);

            if (dic != null)
            {
                Model.member member;
                if (mbll.ExistsQQOpenid(openid))
                {
                    member = mbll.GetModelByOpenid(openid);

                    if (member.status == (int)Enums.MemberStatus.人工审核)
                    {
                        Response.Redirect("/user/reg_check.aspx?status=" + Enums.MemberStatus.人工审核.ToString());
                    }
                    else if (member.status == (int)Enums.MemberStatus.冻结)
                    {
                        Response.Redirect("/user/reg_check.aspx?status=" + Enums.MemberStatus.冻结.ToString());
                    }
                    else
                    {
                        member.figure_url = dic["figureurl_2"].ToString();
                        member.last_time = member.this_time;
                        member.this_time = DateTime.Now.ToString();
                        member.last_ip = member.this_ip;
                        member.this_ip = Request.UserHostAddress;
                        mbll.Update(member);

                        //设置验证Cookie并跳转
                        CookieHelper.Set("username", member.user_name);
                        FormsAuthentication.RedirectFromLoginPage(member.user_name, false);
                    }
                }
                else
                {
                    ltrFigure.Text = string.Format("<img src=\"{0}\" /><br />{1}", dic["figureurl_1"], dic["nickname"]);
                }

            }
            else
            {
                Response.Write("获取user_info失败！");
                Response.End();
            }
        }
    }
}